package top.idetect.client.modules.cloth.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.idetect.client.common.api.CommonResult;
import top.idetect.client.modules.cloth.model.Clothinfo;
import top.idetect.client.modules.cloth.model.DynamicConfig;
import top.idetect.client.modules.cloth.model.Flaw;
import top.idetect.client.modules.cloth.service.ClothinfoService;
import top.idetect.client.modules.cloth.service.DynamicConfigService;
import top.idetect.client.modules.cloth.service.FlawService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/dataUpload")
public class dataUploadController {

    @Autowired
    private FlawService flawService;

    @Autowired
    private ClothinfoService clothinfoService;

    @Autowired
    private DynamicConfigService dynamicConfigService;

    @ApiOperation("终端数据以HTTP协议上传至云端")
    @PostMapping("/tongbo")
    @ResponseBody
    public CommonResult tongbo(@RequestBody Map<String, Object> data) {
        Object type = data.get("type");
        if (type.equals("cloth")) {
            Clothinfo clothinfo = JSONObject.parseObject(JSONObject.toJSONString(data.get("clothinfo")), Clothinfo.class);
            Clothinfo clothinfoTemp = clothinfoService.getByClothSerial(clothinfo.getClothSerial());
            if(clothinfoTemp != null){
                clothinfo.setId(clothinfoTemp.getId());
            }
            if(clothinfo.getClothWidth() == null || clothinfo.getClothWidth().equals(0.00)){
                DynamicConfig defaultClothWidth = dynamicConfigService.getByConfigName("default_cloth_width");
                clothinfo.setClothWidth(Double.parseDouble(defaultClothWidth.getConfigValue()));
            }
            if(clothinfo.getTimestamp() == null){
                clothinfo.setTimestamp(clothinfo.getBeginTime());
            }
            log.info("clothinfo: " + JSONObject.toJSONString(clothinfo));
            clothinfoService.saveOrUpdate(clothinfo);

        } else if (type.equals("flaw")) {
            List<Flaw> flaws = JSONObject.parseObject(JSONObject.toJSONString(data.get("flaws")), ArrayList.class);
            flawService.saveBatch(flaws);
            Flaw temp = JSONObject.parseObject(JSONObject.toJSONString(flaws.get(0)), Flaw.class);
            clothinfoService.updateTotalCount(temp.getClothSerial());
        }
        return CommonResult.success(null);
    }

    @ApiOperation("手动更新批次缺陷总数")
    @PostMapping("/updateClothTotalCount")
    @ResponseBody
    public CommonResult updateClothTotalCount(@RequestParam String clothSerial) {
        clothinfoService.updateTotalCount(clothSerial);
        return CommonResult.success(null);
    }
}
